/*
 * Copyright 2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ideal.ete.collector.Mapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.stereotype.Component;

import com.ideal.ete.collector.application.ApplicationType;
import com.ideal.ete.collector.application.CenterInfo;
import com.ideal.hbase.client.core.mapper.RowMapper;
import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix;

/**
 *
 */
@Component
public class CenterInfoMapper implements RowMapper<List<CenterInfo>> {

	private RowKeyDistributorByHashPrefix rowKeyDistributorByHashPrefix;

	public RowKeyDistributorByHashPrefix getRowKeyDistributorByHashPrefix() {
		return rowKeyDistributorByHashPrefix;
	}

	public void setRowKeyDistributorByHashPrefix(RowKeyDistributorByHashPrefix rowKeyDistributorByHashPrefix) {
		this.rowKeyDistributorByHashPrefix = rowKeyDistributorByHashPrefix;
	}

	@Override
	public List<CenterInfo> mapRow(Result result, int rowNum) throws Exception {
		if (result.isEmpty()) {
			return Collections.emptyList();
		}
		String center = Bytes.toString(result.getRow());

		Cell[] rawCells = result.rawCells();
		List<CenterInfo> centerInfoList = new ArrayList<>();
		for (Cell cell : rawCells) {
			CenterInfo centerInfo = new CenterInfo();
			String value = Bytes.toString(CellUtil.cloneValue(cell));
			String agentId = Bytes.toString(CellUtil.cloneQualifier(cell));
			long timestamp = cell.getTimestamp();
			centerInfo.setCenter(center);
			ApplicationType applicationType = new ApplicationType();
			String[] split = value.split("##");
			applicationType.setType(split[0]);
			applicationType.setApplicationName(split[1]);
			centerInfo.setApplicationType(applicationType);
			centerInfo.setAgentId(agentId);
			centerInfo.setTimeStamp(timestamp);
			centerInfoList.add(centerInfo);

		}

		return centerInfoList;
	}
}
